﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace AccessControl.GateTest
{
    public class GateCommiunicatorListener
    {
        #region Fields

        private int _timeout=10000;
        public int Timeout{
            get { return _timeout=10000; }
            set { _timeout=value; }
        }

        public bool AcceptNewConnections { get; set; }
        #endregion

        #region Events

        public delegate void DataReceivedEventHandler(object sender, string Data);
        public event DataReceivedEventHandler DataReceived;
        public void OnDataReceived(string data){
            if(DataReceived!=null) DataReceived(this, data);
        }
        
        #endregion

        private TcpListener listener;

        public GateCommiunicatorListener(string ipString, int port){
            AcceptNewConnections = true;
            Connect(ipString, port);
        }



        public bool Connect(string ipString, int port)
        {
            if (listener!=null)
                throw new ApplicationException("Gate is already connected!");

            listener = new TcpListener(IPAddress.Any, port);
            var listenThread = new Thread(new ThreadStart(ListenForClients));
            listenThread.Start();

            return true;
        }

        private void ListenForClients()
        {
            listener.Start();


            while (AcceptNewConnections)
            {
                var client = listener.AcceptTcpClient();

                var clientThread=new Thread(new ParameterizedThreadStart(Receive));
                clientThread.Start(client);
            }
        }

        private void Receive(object client)
        {
            var tcpClient = (TcpClient)client;
            var clientStream = tcpClient.GetStream();

            var receiveBuffer = new byte[tcpClient.ReceiveBufferSize];
            var Data="";
            //tcpClient.NoDelay = true;
            while (tcpClient.Connected)
            {
                var availableDataSize = clientStream.Read(receiveBuffer, 0, receiveBuffer.Length);
                Data = Encoding.ASCII.GetString(receiveBuffer);

                OnDataReceived(Data);
            }
        }

        public void Send(string command){
            var data = Encoding.ASCII.GetBytes(command);


            //clientStream.Write(data, 0, data.Length);
        }


        public void Disconnect(){
            //client.Close();
        }
    }
}
